<?php
	/********连接数据库*********/
	//	$dbroot		数据库地址
	//	$dbuser		数据库账号
	//	$dbpwd		数据库密码
	//	$db			要用的数据库
		
	function connect($dbroot,$dbuser,$dbpwd,$db){
		
		$con = mysqli_connect($dbroot,$dbuser,$dbpwd,$db);
		
		if(!$con){
			mysqli_connect_error($con);
		}
		mysqli_set_charset($con,'utf8');
		
		
		return $con;
		
	}
	/***********插入数据**************/
	//$con		链接语柄
	//$table	插入数据的数据表
	//$field	插入数据组成的数组
	
	function dbinsert($con,$table,$field){
//		$num = func_num_args()-1;
//		$t = time();
		$keys = implode(',',array_keys($field));
		$values = "'".implode("','",array_values($field))."'";
		
		$sql = "insert into {$table}({$keys}) value({$values})";
		
		// var_dump($sql);die;
		$query = mysqli_query($con,$sql);
		$rows = mysqli_affected_rows($con);
		
		
//		if($rows>0){
//			echo '插入'.$rows.'条数据';
//		}else{
//			echo '插入失败';
//		}
//		$sql = "insert into news(newtitle,newcont,newdate) value('{$newtit}','{$newtext}','{$newdate}')";
//		$sql = 'insert into {$table}()'
		return $rows;
		
	}
	/*************删除数据****************/
	//$con		链接语柄
	//$table	删除数据的数据表
	//$where	删除条件
	
	function dbdelete($con,$table,$where=null){
		if($where){
			$where = 'where '.$where;
		}
		$sql = "delete from {$table} {$where}";
		$query = mysqli_query($con,$sql);
		$rows = mysqli_affected_rows($con);
		
		return $rows;
	}




	/***************查询数据库******************/
	//	$con	连接语柄
	//	$table	查询数据表
	//	$field	查询的字段
	//	$where	查询的条件
	//	$order	查询的顺序
	// 	$limit	查询的数目
	
	function dbselect($con,$table,$field='*',$where='',$order='',$limit=''){
		
		if($where){
			$wh= "where ".$where;
		}else{
			$wh = '';
		}
		if($order){
			$orders = "order by ".$order;
		}else{
			$orders = '';
		}
		if($limit){
			$li = "limit ".$limit;
		}else{
			$li = '';
		}
		
		$sql = "select {$field} from {$table} {$wh} {$orders} {$li} ";

		
		
		$result = mysqli_query($con,$sql);
		$data = array();
		
		if($result){
			while($row = mysqli_fetch_assoc($result)){
			$data[] = $row; 
		}
		}
		
		return $data;
	};
	


	//单条查询
	function dbselOne($con,$table,$field='*',$id){
		
		$sql = "select {$field} from {$table} where id={$id} ";

		$result = mysqli_query($con,$sql);
		
		$data = mysqli_fetch_assoc($result);

		return $data;
		
		
	};

	/***************更改数据******************/
	//$con		链接语柄
	//$table	更新的数据表
	//$field	更改的数据的数组
	//$where	更改条件
	
	function dbupdate($con,$table,$field,$where=null){
		$where = $where == null?null:'where '.$where;
		
		$str = '';
		foreach($field as $keys => $vals){
			if($str){
				$sep = ',';
			}else{
				$sep = '';
			}
			$str .= $sep.$keys."='".$vals."'";
		}
		
		
		$sql = "update {$table} set {$str} {$where}";
		
		$query = mysqli_query($con,$sql);
		return $rows = mysqli_affected_rows($con);
		if($rows>0){
			echo '更新'.$rows.'条数据';
		}else{
			echo '更新失败';
		}
	}
	
	
?>